﻿/*
* Activity Tracking Log v0.1.1 - http://activitytrackinglog.codeplex.com
* Activity Tracking Log for ASP.Net & ASP.Net MVC
* Copyright (c) 2011 Vadim Burac
* Licensed under the Microsoft Public License (Ms-PL)
* http://activitytrackinglog.codeplex.com/license
*/

using System;
using System.Web;
using System.Web.SessionState;
using ActivityTrackingLog.Utils;
using ActivityTrackingLog.Configuration;

namespace ActivityTrackingLog.Web
{
    public class SystemEventsLoggingModule : IHttpModule, IReadOnlySessionState
    {
        /// <summary>
        /// You will need to configure this module in the web.config file of your
        /// web and register it with IIS before being able to use it. For more information
        /// see the following link: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpModule Members

        public void Dispose()
        {
            //clean-up code here.
        }

        public void Init(HttpApplication app)
        {
            if (!Config.Log.Enabled || !Config.Log.LogSystemEvents)
                return;

            // handle predefined/custom events 
            if (Config.Log.LogSessionEvents)
            {
                // session state
                app.PostAcquireRequestState += new EventHandler(App_Handler);
                app.PostReleaseRequestState += new EventHandler(App_Handler);
            }
            if (Config.Log.LogRequestEvents)
            {
                // request specific actions
                app.BeginRequest += new EventHandler(App_Handler);
                app.EndRequest += new EventHandler(App_Handler);
            }
            if (Config.Log.LogAuthEvents)
            {
                // auth/auth
                app.PostAuthenticateRequest += new EventHandler(App_Handler);
                app.PostAuthorizeRequest += new EventHandler(App_Handler);
                app.PostLogRequest += new EventHandler(App_Handler);
            }
        }

        #endregion

        public void App_Handler(object source, EventArgs e)
        {
            HttpApplication app = (HttpApplication)source;
            HttpContext context = app.Context;
            if (context.Request.RawUrl.ToLower().Contains(".axd"))
            {
                // TODO: implement configurable Regex rule based filter 
                return;
            }

            ActivityTypeEnum type = ActivityTypeEnum.System;
            Log.LogActivity(type, context.CurrentNotification.ToString(), true, null, false, ((int)context.CurrentNotification).ToString());
        }
    }
}
